package com.lehecai.core.servlet;

import com.lehecai.core.exception.RequestParameterException;
import com.lehecai.core.util.CharsetConstant;
import net.sf.json.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 基础Servlet
 * 封装统一的获取Spring上下文方法
 * 封装统一的输出方法
 * @author Sunshow
 * 
 */
public abstract class CoreBaseServlet extends HttpServlet {

    private static final long serialVersionUID = -1824985097432293183L;

    protected final Logger logger = LoggerFactory.getLogger(this.getClass().getName());

	protected void writeRs(HttpServletResponse response, JSON rs) {
		writeRs(response, rs.toString());
	}

    protected String getCharset() {
        return CharsetConstant.CHARSET_UTF8;
    }

    protected boolean useCache() {
        return false;
    }

	protected void writeRs(HttpServletResponse response, String rs) {
        if (!this.useCache()) {
            response.setContentType("text/html;charset=" + this.getCharset());
            response.setCharacterEncoding(this.getCharset());
            response.addHeader("Expires", "0");
            response.addHeader("Cache-Control","no-store, no-cache, must-revalidate");
            response.addHeader("Pragma", "no-cache");
        }
		try {
			response.getWriter().print(rs);
			response.getWriter().close();
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
	}

	@Override
	abstract protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	protected ParameterValidateRule[] getParameterValidateRules() {
		return null;
	}

	protected Map<String, Object> validateParameterResult(HttpServletRequest request) throws RequestParameterException {
		ParameterValidateRule[] rules = this.getParameterValidateRules();
        return ParameterValidateRule.validateRequestParameterResult(rules, request);
	}
}

